import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  UnauthorizedException,
  SetMetadata,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ResultCode } from '../../common/result/ResultCode';
import { JwtUtils } from '../../modules/01_auth/jwt.utils';

export const RequiredPermission = (permission: string) =>
  SetMetadata('requiredPermission', permission);

@Injectable()
export class AuthInterceptor implements NestInterceptor {
  constructor(private readonly jwt?: JwtUtils) {}
  async intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.authorization;
    const result = await this.jwt.verify(token);
    if (result != ResultCode.SUCCESS) {
      throw new UnauthorizedException(result);
    }
    const currentUser = await this.jwt.decodeToken(token);

    // 验证perm属性
    const requiredPermission = Reflect.getMetadata(
      'requiredPermission',
      context.getHandler(),
    );
    // console.log(requiredPermission);
    // console.log(currentUser.perms);
    // 如果perm不为空，校验perm信息
    if (requiredPermission && !currentUser.perms.includes(requiredPermission)) {
      throw new UnauthorizedException(ResultCode.AUTHORIZED_ERROR);
    }
    request.user = currentUser;
    // 如果是插入操作，注入createUser
    if (request.method === 'POST') {
      request.body.createBy = currentUser.userId;
      request.body.createUser = currentUser.nickname;
      request.body.updateBy = currentUser.userId;
      request.body.updateUser = currentUser.nickname;
    }

    // 如果是更新操作，注入updateUser
    if (request.method === 'PUT') {
      request.body.updateBy = currentUser.userId;
      request.body.updateUser = currentUser.nickname;
    }

    return next.handle().pipe(
      map((data) => {
        // 这里你可以根据需要对响应数据进行处理
        return data;
      }),
    );
  }
}
